import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

public class Manager extends User{
    private Map<String,User> users;
    private List<Movie> movies;
    private List<Screening> screenings;
    private List<Ticket> tickets;

    public Manager(String userId, String username, String password, String phone,
                   Map<String, User> users, List<Movie> movies, List<Screening> screenings, List<Ticket> tickets) {
        super(userId,username,password,UserType.MANAGER,phone);
        this.users = users;
        this.movies = movies;
        this.screenings = screenings;
        this.tickets = tickets;
    }

    @Override
    public void menu(){
        while(true) {
            System.out.println("\n===== 经理菜单 =====");
            System.out.println("1. 密码管理");
            System.out.println("2. 影片管理");
            System.out.println("3. 排片管理");
            System.out.println("4. 查看销售数据");
            System.out.println("5. 退出登录");
            System.out.print("请选择: ");
            try {
                int choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        managerPasswordManagement();
                        break;
                    case 2:
                        movieManagement();
                        break;
                    case 3:
                        screeningManagement();
                        break;
                    case 4:
                        viewSalesData();
                        break;
                    case 5:
                        return;
                    default:
                        System.out.println("无效选择");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }
    }

    // 经理密码管理
    private void managerPasswordManagement(){
        while (true) {
            System.out.println("\n===== 密码管理 =====");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置前台密码");
            System.out.println("3. 退出");
            System.out.print("请选择: ");

            try {
                int choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        changeOwnPassword();
                        break;
                    case 2:
                        resetFrontDeskPassword();
                        break;
                    case 3:
                        return;
                    default:
                        System.out.println("无效选择");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }
    }
    // 重置前台密码
    private void resetFrontDeskPassword(){
        System.out.print("请输入要重置密码的前台用户ID: ");
        String userId=scanner.nextLine();

        User user=users.get(userId);
        if (user==null) {
            System.out.println("用户不存在");
            return;
        }

        if (user.getUserType() != UserType.FRONT_DESK) {
            System.out.println("只能重置前台用户密码");
            return;
        }

        user.password = "123456"; // 重置密码
        System.out.println("前台用户 " + user.getUsername() + " 的密码已重置为 123456");
        Logger.log("重置前台密码: " + user.getUsername(),this.getUsername());
    }

    // 列出所有影片
    private void listAllMovies() {
        System.out.println("\n===== 影片列表 =====");
        System.out.printf("%-10s %-20s %-15s %-30s %-8s %-5s%n",
                "电影ID", "片名", "导演", "主演", "时长(分)", "评分");

        for (Movie movie : movies) {
            System.out.printf("%-10s %-20s %-15s %-30s %-8d %-5.1f%n",
                    movie.getMovieId(),
                    movie.getTitle(),
                    movie.getDirector(),
                    movie.getActors().length() > 25 ? movie.getActors().substring(0, 25) + "..." : movie.getActors(),
                    movie.getDuration(),
                    movie.getRating());
        }
    }

    // 列出场次
    private void listScreenings() {
        System.out.println("\n===== 场次列表 =====");
        System.out.printf("%-10s %-20s %-15s %-20s %-10s %-10s%n",
                "场次ID", "电影", "放映厅", "时间", "票价", "剩余座位");

        for (Screening screening : screenings) {
            System.out.printf("%-10s %-20s %-15s %-20s %-10.2f %-10d%n",
                    screening.getScreeningId(),
                    screening.getMovie().getTitle(),
                    screening.getHall().getName(),
                    screening.getStartTime().toString(),
                    screening.getPrice(),
                    screening.getAvailableSeatsCount());
        }
    }

    // 影片管理
    private void movieManagement() {
        while (true) {
            System.out.println("\n===== 影片管理 =====");
            System.out.println("1. 列出所有影片");
            System.out.println("2. 添加影片");
            System.out.println("3. 修改影片");
            System.out.println("4. 删除影片");
            System.out.println("5. 查询影片");
            System.out.println("6. 退出");
            System.out.print("请选择: ");

            try {
                int choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        listAllMovies();
                        break;
                    case 2:
                        addMovie();
                        break;
                    case 3:
                        updateMovie();
                        break;
                    case 4:
                        deleteMovie();
                        break;
                    case 5:
                        searchMovie();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("无效选择");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }
    }
    // 添加影片
    private void addMovie() {
        System.out.println("\n===== 添加影片 =====");
        System.out.print("电影ID: ");
        String movieId = scanner.nextLine();

        // 检查电影ID唯一性
        for (Movie movie : movies) {
            if (movie.getMovieId().equals(movieId)) {
                System.out.println("电影ID已存在");
                return;
            }
        }

        System.out.print("片名: ");
        String title = scanner.nextLine();

        System.out.print("导演: ");
        String director = scanner.nextLine();

        System.out.print("主演: ");
        String actors = scanner.nextLine();

        System.out.print("剧情简介: ");
        String description = scanner.nextLine();

        System.out.print("时长(分钟): ");
        int duration = Integer.parseInt(scanner.nextLine());

        System.out.print("评分(0-10): ");
        double rating = Double.parseDouble(scanner.nextLine());

        Movie newMovie = new Movie(movieId, title, director, actors, description, duration, rating);
        movies.add(newMovie);
        System.out.println("影片添加成功");
    }

    // 修改影片
    private void updateMovie() {
        System.out.println("\n===== 修改影片 =====");
        System.out.print("请输入要修改的电影ID: ");
        String movieId = scanner.nextLine();

        Movie movieToUpdate = null;
        for (Movie movie : movies) {
            if (movie.getMovieId().equals(movieId)) {
                movieToUpdate = movie;
                break;
            }
        }

        if (movieToUpdate == null) {
            System.out.println("电影不存在");
            return;
        }

        System.out.println("当前信息:");
        System.out.println("片名: " + movieToUpdate.getTitle());
        System.out.println("导演: " + movieToUpdate.getDirector());
        System.out.println("主演: " + movieToUpdate.getActors());
        System.out.println("剧情简介: " + movieToUpdate.getDescription());
        System.out.println("时长: " + movieToUpdate.getDuration());
        System.out.println("评分: " + movieToUpdate.getRating());

        System.out.print("输入新片名(留空不修改): ");
        String newTitle = scanner.nextLine();
        if (!newTitle.isEmpty()) {
            movieToUpdate.setTitle(newTitle);
        }

        System.out.print("输入新导演(留空不修改): ");
        String newDirector = scanner.nextLine();
        if (!newDirector.isEmpty()) {
            movieToUpdate.setDirector(newDirector);
        }

        System.out.print("输入新主演(留空不修改): ");
        String newActors = scanner.nextLine();
        if (!newActors.isEmpty()) {
            movieToUpdate.setActors(newActors);
        }

        System.out.print("输入新剧情简介(留空不修改): ");
        String newDescription = scanner.nextLine();
        if (!newDescription.isEmpty()) {
            movieToUpdate.setDescription(newDescription);
        }

        System.out.print("输入新时长(分钟, 0表示不修改): ");
        int newDuration = Integer.parseInt(scanner.nextLine());
        if (newDuration > 0) {
            movieToUpdate.setDuration(newDuration);
        }

        System.out.print("输入新评分(0-10, -1表示不修改): ");
        double newRating = Double.parseDouble(scanner.nextLine());
        if (newRating >= 0 && newRating <= 10) {
            movieToUpdate.setRating(newRating);
        }

        System.out.println("影片信息修改成功");
    }

    // 删除影片
    private void deleteMovie() {
        System.out.println("\n===== 删除影片 =====");
        System.out.print("请输入要删除的电影ID: ");
        String movieId = scanner.nextLine();

        Movie movieToDelete = null;
        for (Movie movie : movies) {
            if (movie.getMovieId().equals(movieId)) {
                movieToDelete = movie;
                break;
            }
        }

        if (movieToDelete == null) {
            System.out.println("电影不存在");
            return;
        }

        // 检查是否有场次使用该电影
        for (Screening screening : screenings) {
            if (screening.getMovie().getMovieId().equals(movieId)) {
                System.out.println("该电影有排片，不能删除");
                return;
            }
        }

        System.out.print("确定要删除电影 " + movieToDelete.getTitle() + " 吗? (y/n): ");
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            movies.remove(movieToDelete);
            System.out.println("影片删除成功");
        } else {
            System.out.println("取消删除");
        }
    }

    // 查询影片
    private void searchMovie(){
        System.out.println("\n===== 查询影片 =====");
        System.out.print("请输入关键字(片名/导演/主演): ");
        String keyword = scanner.nextLine().toLowerCase();

        System.out.printf("%-10s %-20s %-15s %-30s %-8s %-5s%n",
                "电影ID", "片名", "导演", "主演", "时长(分)", "评分");

        for (Movie movie : movies) {
            if (movie.getTitle().toLowerCase().contains(keyword) ||
                    movie.getDirector().toLowerCase().contains(keyword) ||
                    movie.getActors().toLowerCase().contains(keyword)) {

                System.out.printf("%-10s %-20s %-15s %-30s %-8d %-5.1f%n",
                        movie.getMovieId(),
                        movie.getTitle(),
                        movie.getDirector(),
                        movie.getActors().length() > 25 ? movie.getActors().substring(0, 25) + "..." : movie.getActors(),
                        movie.getDuration(),
                        movie.getRating());
            }
        }
    }

    // 排片管理
    private void screeningManagement() {
        while (true) {
            System.out.println("\n===== 排片管理 =====");
            System.out.println("1. 增加场次");
            System.out.println("2. 修改场次");
            System.out.println("3. 删除场次");
            System.out.println("4. 列出所有场次");
            System.out.println("5. 自动排片");
            System.out.println("6. 退出");
            System.out.print("请选择: ");

            try {
                int choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        addScreening();
                        break;
                    case 2:
                        updateScreening();
                        break;
                    case 3:
                        deleteScreening();
                        break;
                    case 4:
                        listScreenings();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("无效选择");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }
    }
    // 增加场次
    private void addScreening() {
        System.out.println("\n===== 增加场次 =====");

        listAllMovies();
        System.out.print("请输入电影ID: ");
        String movieId = scanner.nextLine();

        Movie selectedMovie = null;
        for (Movie movie : movies) {
            if (movie.getMovieId().equals(movieId)) {
                selectedMovie = movie;
                break;
            }
        }

        if (selectedMovie == null) {
            System.out.println("电影不存在");
            return;
        }

        System.out.println("放映厅选择:");
        for (HallType hall : HallType.values()) {
            System.out.println(hall.ordinal() + 1 + ". " + hall.getName() + " (" + hall.getCapacity() + "座)");
        }
        System.out.print("请选择放映厅(1-" + HallType.values().length + "): ");
        int hallChoice = Integer.parseInt(scanner.nextLine()) - 1;

        if (hallChoice < 0 || hallChoice >= HallType.values().length) {
            System.out.println("无效选择");
            return;
        }
        HallType hallType = HallType.values()[hallChoice];

        System.out.print("输入日期 (yyyy-MM-dd): ");
        String dateStr = scanner.nextLine();
        System.out.print("输入时间 (HH:mm): ");
        String timeStr = scanner.nextLine();

        LocalDateTime startTime;
        try {
            LocalDate date = LocalDate.parse(dateStr);
            LocalTime time = LocalTime.parse(timeStr);
            startTime = LocalDateTime.of(date, time);
        } catch (Exception e) {
            System.out.println("日期格式错误");
            return;
        }

        for (Screening screening : screenings) {
            if (screening.getHall() == hallType &&
                    screening.getStartTime().equals(startTime)) {
                System.out.println("该放映厅此时段已有排片");
                return;
            }
        }

        System.out.print("输入票价: ");
        double price = Double.parseDouble(scanner.nextLine());

        String screeningId = "scr" + (screenings.size() + 1);
        Screening newScreening = new Screening(screeningId, selectedMovie, hallType, startTime, price);
        screenings.add(newScreening);
        System.out.println("场次添加成功");
    }

    // 修改场次
    private void updateScreening() {
        System.out.println("\n===== 修改场次 =====");
        listScreenings();
        System.out.print("请输入要修改的场次ID: ");
        String screeningId = scanner.nextLine();

        Screening screeningToUpdate = null;
        for (Screening screening : screenings) {
            if (screening.getScreeningId().equals(screeningId)) {
                screeningToUpdate = screening;
                break;
            }
        }

        if (screeningToUpdate == null) {
            System.out.println("场次不存在");
            return;
        }

        for (Ticket ticket : tickets) {
            if (ticket.getScreening().getScreeningId().equals(screeningId) && !ticket.isRefunded()) {
                System.out.println("该场次已有票售出，不能修改");
                return;
            }
        }

        listAllMovies();
        System.out.print("请输入新电影ID(留空不修改): ");
        String newMovieId = scanner.nextLine();

        if (!newMovieId.isEmpty()) {
            Movie newMovie = null;
            for (Movie movie : movies) {
                if (movie.getMovieId().equals(newMovieId)) {
                    newMovie = movie;
                    break;
                }
            }
            if (newMovie != null) {
                screeningToUpdate.movie = newMovie;
            }
        }

        System.out.print("输入新票价(0表示不修改): ");
        double newPrice = Double.parseDouble(scanner.nextLine());
        if (newPrice > 0) {
            screeningToUpdate.price = newPrice;
        }

        System.out.println("场次修改成功");
        Logger.log("修改场次: " + screeningId, this.getUsername());
    }

    // 删除场次
    private void deleteScreening() {
        System.out.println("\n===== 删除场次 =====");
        listScreenings();
        System.out.print("请输入要删除的场次ID: ");
        String screeningId = scanner.nextLine();

        Screening screeningToDelete = null;
        for (Screening screening : screenings) {
            if (screening.getScreeningId().equals(screeningId)) {
                screeningToDelete = screening;
                break;
            }
        }

        if (screeningToDelete == null) {
            System.out.println("场次不存在");
            return;
        }

        for (Ticket ticket : tickets) {
            if (ticket.getScreening().getScreeningId().equals(screeningId) && !ticket.isRefunded()) {
                System.out.println("该场次已有票售出，不能删除");
                return;
            }
        }

        System.out.print("确定要删除场次 " + screeningId + " 吗? (y/n): ");
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            screenings.remove(screeningToDelete);
            System.out.println("场次删除成功");
            Logger.log("删除场次: " + screeningId, this.getUsername());
        } else {
            System.out.println("取消删除");
        }
    }

    // 查看销售数据
    private void viewSalesData() {
        while (true) {
            System.out.println("\n===== 查看销售数据 =====");
            System.out.println("1. 当日销售数据");
            System.out.println("2. 当周销售数据");
            System.out.println("3. 当月销售数据");
            System.out.println("4. 退出");
            System.out.print("请选择: ");

            try {
                int choice = Integer.parseInt(scanner.nextLine());
                LocalDate today = LocalDate.now();

                switch (choice) {
                    case 1:
                        showSalesData(today, today);
                        break;
                    case 2:
                        showSalesData(today.minusDays(7), today);
                        break;
                    case 3:
                        showSalesData(today.minusDays(30), today);
                        break;
                    case 4:
                        return;
                    default:
                        System.out.println("无效选择");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }
    }

    // 显示销售数据
    private void showSalesData(LocalDate startDate, LocalDate endDate) {
        int totalTickets = 0;
        double totalRevenue = 0;
        int refundedTickets = 0;
        double refundedAmount = 0;

        for (Ticket ticket : tickets) {
            LocalDate ticketDate = ticket.getPurchaseTime().toLocalDate();
            if (!ticketDate.isBefore(startDate) && !ticketDate.isAfter(endDate)) {
                if (ticket.isRefunded()) {
                    refundedTickets++;
                    refundedAmount += ticket.getTotalPrice();
                } else {
                    totalTickets++;
                    totalRevenue += ticket.getTotalPrice();
                }
            }
        }

        System.out.println("\n===== 销售数据统计 (" + startDate + " 至 " + endDate + ") =====");
        System.out.println("总售票数: " + totalTickets);
        System.out.println("总售票金额: " + totalRevenue);
        System.out.println("总退票数: " + refundedTickets);
        System.out.println("退票金额: " + refundedAmount);
        System.out.println("净销售额: " + (totalRevenue - refundedAmount));
    }

}


